package com.lemon.tuvi2015;

import java.util.ArrayList;

import org.json.JSONException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.lemon.tuvi2015.object.DetailsObject;
import com.lemon.tuvi2015.object.GlobalObject;
import com.lemon.tuvi2015.util.BaseEngine;
import com.lemon.tuvi2015.util.CMD;
import com.lemon.tuvi2015.util.JsonParser;
import com.lemon.tuvi2015.util.TagName;
import com.lemon.tuvi2015.view.CustomActionbar;

@SuppressLint("NewApi") public class ZodiacDetailsActivity extends Activity {
	GlobalObject zodiacObject;
	CustomActionbar actionbar;
	WebView webView;
	ProgressBar progressBar;
	String cmd = CMD.ITEM_DETALS;
	LinearLayout linearLayout;
	String data;
	View main;
	String title;
	TextView textView,textViewContent;
	ScrollView scrollView;
	Handler handler=new Handler();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.horoscope_details);

		initView();
		Bundle extras = getIntent().getExtras();
		if (getIntent().hasExtra(TagName.OBJ))
			zodiacObject = (GlobalObject) extras.getSerializable(TagName.OBJ);
		if (getIntent().hasExtra(TagName.KEY))
			cmd = extras.getString(TagName.KEY);
		if (getIntent().hasExtra(TagName.TITLE))
			title = extras.getString(TagName.TITLE);
		initActionbar();

		if (zodiacObject != null && !zodiacObject.getID().equals(""))
			new AsyncTaskParseJson().execute("");
	}

	void initView() {
		scrollView=(ScrollView) findViewById(R.id.scrollview);
		linearLayout = (LinearLayout) findViewById(R.id.layout_content);
		textViewContent=(TextView) findViewById(R.id.textViewContent);
		textView=(TextView) findViewById(R.id.textView);
		textView.setVisibility(View.GONE);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		webView = (WebView) findViewById(R.id.webView);
		webView.setVisibility(View.VISIBLE);
		webView.setWebViewClient(new WebViewClient() {

			public void onPageFinished(WebView view, String url) {
				webView.setVisibility(View.VISIBLE);
				if (cmd.equals(CMD.SMSKUTE_DETAILS)){
					webView.setVisibility(View.GONE);
					 Thread t =new Thread(){
					        public void run() {
					            handler.postDelayed(new Runnable() {
					                public void run() {
					                	linearLayout.setVisibility(View.VISIBLE);
					                }
					            },2000);
					        }
					    };
					    t.start();
				}
				progressBar.setVisibility(View.GONE);
			}
		});
		webView.setBackgroundColor(Color.TRANSPARENT);
//		webView.setBackgroundColor(Color.parseColor("#919191"));
		    if (Build.VERSION.SDK_INT >= 11) {
		    	webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
		    }
		main=findViewById(R.id.main);
		
		((Button) findViewById(R.id.buttonCopy)).setOnClickListener(clickListener);
		((Button) findViewById(R.id.buttonSendsms)).setOnClickListener(clickListener);
	}

	OnClickListener clickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.buttonCopy:
				copy(data);
				break;
			case R.id.buttonSendsms:
				BaseEngine.sendSMS(ZodiacDetailsActivity.this, data);
				break;

			default:
				break;
			}
		}
	};

	void initActionbar() {
		actionbar = (CustomActionbar) findViewById(R.id.header);
		OnClickListener listenerBack = new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		};
		OnClickListener listenerShare = new OnClickListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				BaseEngine.shareBitmap(ZodiacDetailsActivity.this,  BaseEngine.ConvertViewtoBitmap(ZodiacDetailsActivity.this, main));
			}
		};
		
		if (zodiacObject != null && !zodiacObject.getNAME().equals(""))
			if (!cmd.equals(CMD.ITEM_DETALS))
				actionbar.setActionbar(zodiacObject.getNAME(), listenerBack, listenerShare);
			else
				actionbar.setActionbar(title + zodiacObject.getNAME(), listenerBack, listenerShare);
		else
			actionbar.setActionbar(R.string.home_menu_congiap, listenerBack, listenerShare);
	}

	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	void copy(String text) {
		String copied = "Đã chép tin nhắn";
		int sdk = android.os.Build.VERSION.SDK_INT;
		if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
			android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
			clipboard.setText(text);
			Toast.makeText(getApplicationContext(), copied, Toast.LENGTH_SHORT).show();
		} else {
			android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
			android.content.ClipData clip = android.content.ClipData.newPlainText("sms", text);
			clipboard.setPrimaryClip(clip);
			Toast.makeText(getApplicationContext(), copied, Toast.LENGTH_SHORT).show();
		}
	}

	private void showContent(DetailsObject detailsObject) {
		if (cmd.equals(CMD.SMSKUTE_DETAILS)) {
			if (scrollView!=null)
				scrollView.setVisibility(View.VISIBLE);
			textViewContent.setText(detailsObject.getcontent());
		}
		final String mimeType = "text/html";
		final String encoding = "utf-8";
//		data = Html.fromHtml(detailsObject.getcontent()).toString();
		data=detailsObject.getcontent();
		webView.loadDataWithBaseURL(null, data, mimeType, encoding, null);
	}

	public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
		}

		@Override
		protected String doInBackground(String... arg0) {
			String str = JsonParser.getJson(cmd, zodiacObject.getID());
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			
			if (result != null) {
//				 BaseEngine.showLogformLongString("", result);
				if (cmd.equals(CMD.SMSKUTE_DETAILS)) {
					ViewGroup.LayoutParams layoutParams = (ViewGroup.LayoutParams) linearLayout.getLayoutParams();
					layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
					linearLayout.requestLayout();
				}
				try {
					if (!JsonParser.readStatus(result).equals("")) {
						ArrayList<DetailsObject> arrayList = JsonParser.readDetails(result);
						if (arrayList != null && arrayList.size() > 0) {
							showContent(arrayList.get(0));
						}else
							showErr();
					}else{
						showErr();
					}
				} catch (JSONException e) {
					e.printStackTrace();
					showErr();
				}
			}
		}
	}
	
	void showErr(){
		String err="Dữ liệu đang cập nhật!";
		progressBar.setVisibility(View.GONE);
		textView.setText(err);
	}
}
